//
//  EditEmailViewController.m
//  cliqset
//
//  Created by David Hinson on 2/18/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "EditEmailViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"

@implementation EditEmailViewController

@synthesize emailAddresses;
@synthesize emailAddressField;
@synthesize emailTypeField;
@synthesize parent;
@synthesize valid;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Edit Email";
	
	self.emailAddresses.backgroundColor = [UIColor clearColor];
	
	// Set save button
	UIBarButtonItem* saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	// Set cancel button
	UIBarButtonItem* cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
	self.navigationItem.leftBarButtonItem = cancelButton;
	
	// For our valid entries
	valid = [[NSMutableArray alloc] init];
	
	if (parent.isPersonal) {
		[valid addObject:@"personal"];
		}
	else {
		[valid addObject:@"work"];
		}
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"doCancel");
	
	[myApp slideEmailOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([self.emailAddressField isEqualToString:@""]) {
		[myApp addTextToLog:@"Email Address Cannot Be Empty!" withCaption:@"Edit Email" ];
		return;
	}
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.parent.index >= 0) {
		if (parent.isFavorite) {
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:parent.index]]) {
					contact = localContact;
					break;
					}
				}
			} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:parent.index];
			}
	} else {
		contact = self.parent.bufferContact;
	}
	
	NSLog(@"doSave");
	
	// Add through cliqset, if this is an update
	if (self.parent.index >= 0) {
		[myApp.cliqset putEmail:contact.contactIdentifier tag:[self.emailTypeField capitalizedString] number:self.emailAddressField primary:NO];
		}
	
	// And add back to contact email addresses array
	EmailAddress * email = [[EmailAddress alloc] init];
	
	// Build email entry
	email.type    = (NSMutableString*)[self.emailTypeField capitalizedString];
	email.address = self.emailAddressField;
	email.primary = NO;
	
	// Cycle through addresses... we need to remove any existing with the same type
	for (int x=0; x<[contact.emailAddresses count]; x++) {
		EmailAddress * te = (EmailAddress*)[contact.emailAddresses objectAtIndex:x];
		// NSLog(@"%d  te: [%@] - internal: [%@]", x, te.type, [self.emailTypeField capitalizedString]);
		if ([te.type isEqualToString:[self.emailTypeField capitalizedString]]) {
			[contact.emailAddresses removeObjectAtIndex:x];
			break;
		}
	}
	
	[contact.emailAddresses addObject:email];
	[email release];
	
	[myApp slideEmailOut];
	[parent.contactDetailTable reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	switch (section) {
		case 0:
			return 1.0;
			break;
			
		case 1:
			return 1.0;
			break;
			
		default:
			return 0;
			break;
	}
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	switch (indexPath.section) {
		case 0:
			return 40.0;
			break;
		case 1:
			return 40.0;
			break;
		default:
			break;
	}
	
	return 0.0;
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1 && indexPath.row == 0) {
		return UITableViewCellAccessoryDisclosureIndicator;	
	} 
	else {
		return UITableViewCellAccessoryNone;
	}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	UIFont* large_font      = [UIFont systemFontOfSize:18];
	UIColor* textColor      = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	cell.hidesAccessoryWhenEditing = NO;
	
	UILabel * emailLabel       = [[UILabel alloc] initWithFrame:CGRectMake(20, 7, 290, 26)];
	UITextField * emailAddress = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,46)];
	
	//UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	
	switch (indexPath.section) {
		case 0:
			
			emailAddress.textColor   = textColor;
			emailAddress.font        = large_font;
			emailAddress.placeholder = @"Email";
			
			emailAddress.keyboardType = UIKeyboardTypeEmailAddress;
			emailAddress.autocapitalizationType = UITextAutocapitalizationTypeNone;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emailDidChange:) name:@"UITextFieldTextDidChangeNotification" object:emailAddress];
			emailAddress.text         = (!self.emailAddressField || [self.emailAddressField isEqualToString:@""]) ? @"" : self.emailAddressField;
			
			[emailAddress becomeFirstResponder];
			
			[cell addSubview:emailAddress];
			
			break;
		case 1:
			
			emailLabel.textColor                 = textColor;
			emailLabel.font                      = large_font;
			emailLabel.adjustsFontSizeToFitWidth = NO;
			
			emailLabel.text                      = (!self.emailTypeField || [self.emailTypeField isEqualToString:@""]) ? @"home" : self.emailTypeField;
			self.emailTypeField                  = (NSMutableString*)emailLabel.text;
			
			[cell addSubview:emailLabel];
			break;
	}
	
	[emailLabel release];
	[emailAddress release];

	//cell.backgroundView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
	return cell;
}	

// Row selected... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSLog(@"didSelectRowAtIndexPath");
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	if (indexPath.section == 1) {
		[myApp slideEmailTypeIn:self];
	}
}

// Our email changed... save it
-(void)emailDidChange:(id)textField {	
	self.emailAddressField = (NSMutableString*)[[textField object] text];
}

- (void)dealloc {
	[valid release];
	[parent release];
	[emailAddressField release];
	[emailTypeField release];
	[emailAddresses release];
    [super dealloc];
}


@end
